package wallet

import (
	"gitee.com/magic-mountain/sigs"

	"golang.org/x/xerrors"

	"github.com/filecoin-project/go-address"
	"github.com/filecoin-project/go-state-types/crypto"
)

const (
	KTBLS             string = "bls"
	KTSecp256k1       string = "secp256k1"
	KTSecp256k1Ledger string = "secp256k1-ledger"
)

type KeyInfo struct {
	Type       crypto.SigType
	PrivateKey []byte
}

type Key struct {
	KeyInfo
	PublicKey []byte
	Address   address.Address
}

func GenerateKey(typ crypto.SigType) (*Key, error) {

	if typ == crypto.SigTypeUnknown {
		return nil, xerrors.Errorf("unknown sig type: %s", typ)
	}
	pk, err := sigs.Generate(typ)
	if err != nil {
		return nil, err
	}
	ki := KeyInfo{
		Type:       typ,
		PrivateKey: pk,
	}
	return NewKey(ki)
}

func NewKey(keyinfo KeyInfo) (*Key, error) {
	k := &Key{
		KeyInfo: keyinfo,
	}

	var err error
	k.PublicKey, err = sigs.ToPublic(k.Type, k.PrivateKey)
	if err != nil {
		return nil, err
	}

	switch k.Type {
	case crypto.SigTypeSecp256k1:
		k.Address, err = address.NewSecp256k1Address(k.PublicKey)
		if err != nil {
			return nil, xerrors.Errorf("converting Secp256k1 to address: %w", err)
		}
	case crypto.SigTypeBLS:
		k.Address, err = address.NewBLSAddress(k.PublicKey)
		if err != nil {
			return nil, xerrors.Errorf("converting BLS to address: %w", err)
		}
	default:
		return nil, xerrors.Errorf("unsupported key type: %s", k.Type)
	}
	return k, nil

}

// func ActSigType(typ string) crypto.SigType {
// 	switch typ {
// 	case KTBLS:
// 		return crypto.SigTypeBLS
// 	case KTSecp256k1:
// 		return crypto.SigTypeSecp256k1
// 	default:
// 		return crypto.SigTypeUnknown
// 	}
// }
